package com.smarthealthring.mm.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.exception.BleException;
import com.smarthealthring.mm.R;
import com.smarthealthring.mm.base.BaseActivity;
import com.smarthealthring.mm.base.IPresenter;
import com.smarthealthring.mm.ble.BdProtocol;
import com.smarthealthring.mm.clj.blesample.comm.ObserverManager;
import com.smarthealthring.mm.utils.ComToolBar;
import com.smarthealthring.mm.utils.SPUtils;
import com.smarthealthring.mm.utils.SizeUtils;
import com.smarthealthring.mm.widgets.CustomDialog;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.jakewharton.rxbinding2.view.RxView;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import io.reactivex.functions.Consumer;

/**
 * 判断蓝牙是否连接,去打开蓝牙
 */
public class CheckBtOpenActivity extends BaseActivity {

    @BindView(R.id.btn_open_bt)
    Button mBtnOpenBt;

    private static final int REQUEST_CODE_OPEN_GPS = 1;
    private static final int REQUEST_CODE_PERMISSION_LOCATION = 2;
    private CustomDialog dialog;

    @Override
    protected void initComToolBar() {
        ImageView ivLeft = ComToolBar.setleftImg(mContext, R.drawable.back_white);
        RxView.clicks(ivLeft)
                .subscribe(o -> finish());
    }

    @Override
    protected int getLayout() {
        return R.layout.act_bt_connect;
    }

    @Override
    protected void initEventAndData(@Nullable Bundle savedInstanceState) {
        initDialog();

        RxView.clicks(mBtnOpenBt)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (!BluetoothAdapter.getDefaultAdapter().isEnabled()){
                            mBtnOpenBt.setVisibility(View.VISIBLE);
                        }else {
                            setScanRule();
                            startScan();
                        }
                    }
                });
    }

    public void initDialog() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_set_bluetooth, null);
        View tvCancel = view.findViewById(R.id.tv_cancel_connect_bt);
        View tvConnectBt = view.findViewById(R.id.tv_connect_bt);

        if (dialog == null) {
            dialog = new CustomDialog.Builder(mContext)
                    .setCancelable(false)
                    .setContentView(view)
                    .create();
        }

        RxView.clicks(tvCancel)
                .subscribe(o -> {
                    dialog.dismiss();
                    finish();
                });

        RxView.clicks(tvConnectBt)
                .subscribe(o -> {
                    dialog.dismiss();
//                    checkPermissions();
                });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("requestCode===", requestCode+"");
        Log.e("resultCode===", resultCode+"");
    }

    /**
     * 制定的搜索规则
     */
    private void setScanRule() {
//        String[] uuids;
//        String str_uuid = et_uuid.getText().toString();
//        if (TextUtils.isEmpty(str_uuid)) {
//            uuids = null;
//        } else {
//            uuids = str_uuid.split(",");
//        }
//        UUID[] serviceUuids = null;
//        if (uuids != null && uuids.length > 0) {
//            serviceUuids = new UUID[uuids.length];
//            for (int i = 0; i < uuids.length; i++) {
//                String name = uuids[i];
//                String[] components = name.split("-");
//                if (components.length != 5) {
//                    serviceUuids[i] = null;
//                } else {
//                    serviceUuids[i] = UUID.fromString(uuids[i]);
//                }
//            }
//        }
//
//        String[] names;
//        String str_name = et_name.getText().toString();
//        if (TextUtils.isEmpty(str_name)) {
//            names = null;
//        } else {
//            names = str_name.split(",");
//        }
//
//        String mac = et_mac.getText().toString();
//
//        boolean isAutoConnect = sw_auto.isChecked();

//        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
//                .setServiceUuids(serviceUuids)      // 只扫描指定的服务的设备，可选
//                .setDeviceName(true, names)   // 只扫描指定广播名的设备，可选
//                .setDeviceMac(mac)                  // 只扫描指定mac的设备，可选
//                .setAutoConnect(isAutoConnect)      // 连接时的autoConnect参数，可选，默认false
//                .setScanTimeOut(10000)              // 扫描超时时间，可选，默认10秒
//                .build();
//        BleManager.getInstance().initScanRule(scanRuleConfig);
    }

    /**
     * 蓝牙开启后 跳转搜索列表界面
     */
    private void startScan() {

        //如果已经绑定，直接按mac连设备
//        if(SPUtils.getInt(SPUtils.BOND_STATE,0)==1){
//            BleManager.getInstance().connect(SPUtils.getString(SPUtils.DEVICE_MAC, ""), new BleGattCallback() {
//                @Override
//                public void onStartConnect() {
//                    showLoading(true);
//                }
//
//                @Override
//                public void onConnectFail(BleDevice bleDevice, BleException exception) {
//                    dismissLaoding();
//                    Toast.makeText(mContext, getString(R.string.connect_fail), Toast.LENGTH_LONG).show();
//                }
//
//                @Override
//                public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
//                    dismissLaoding();
////                    mDeviceAdapter.addDevice(bleDevice);
////                    mDeviceAdapter.notifyDataSetChanged();
////
////                    readRssi(bleDevice);
////                    setMtu(bleDevice, 23);
//
//                    //保存下设备信息
//                    SPUtils.setString(SPUtils.DEVICE_MAC, bleDevice.getMac());
//                    SPUtils.setString(SPUtils.DEVICE_NAME, bleDevice.getName());
//                    SPUtils.setInt(SPUtils.DEVICE_RSSI, bleDevice.getRssi());
//
//
//                    BdProtocol.mBluetoothGatt =  BleManager.getInstance().getBluetoothGatt(bleDevice);
//                    Log.e("onConnectSuccess===",bleDevice.getMac()+"---"+bleDevice.getName()+"---"+bleDevice.getRssi());
//
//                }
//
//                @Override
//                public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) {
//                    dismissLaoding();
////                    mDeviceAdapter.removeDevice(bleDevice);
////                    mDeviceAdapter.notifyDataSetChanged();
//
//                    if (isActiveDisConnected) {
//                        Toast.makeText(mContext, getString(R.string.active_disconnected), Toast.LENGTH_LONG).show();
//                    } else {
//                        Toast.makeText(mContext, getString(R.string.disconnected), Toast.LENGTH_LONG).show();
//                        ObserverManager.getInstance().notifyObserver(bleDevice);
//                    }
//
//                }
//            });
//
//        }else {
//            startActivity(new Intent(mContext, SearchBtActivity.class));
//        }
        startActivity(new Intent(mContext, SearchBtActivity.class));
    }


    @Override
    protected IPresenter createPresenter() {
        return null;
    }

}
